package org.android.kumoh_ing;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
/**
 * Map and overlays displaying current location
 *
 * @author Mike
 */
public class SharedLocationActivity extends MapActivity implements AdapterView.OnItemSelectedListener {
	private  List<Overlay> overlays;
    private MapView mapView;
    private MapController mc;
    private Button button;
    private String group_id;
    private String[][] mem;
    private Spinner spinner;
    private String[] locc;
    private String[] name;
    int count=0;
   @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);
        
        mapView = (MapView)findViewById(R.id.map);
        spinner = (Spinner)findViewById(R.id.spinner);
       
        group_id = getIntent().getExtras().getString("group_id");
        
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(false);

        mc = mapView.getController();
        mc.setZoom(17);
        Log.i("Log", "+aaaa");
			Bundle para = new Bundle();
			para.putString("fields", "id,picture,name");
			String responseStr;
			try {
				responseStr = facebookvalue.FacebookInstance.request(group_id + "/members", para);
				JSONObject resultObj = Util.parseJson(responseStr);
				JSONArray jArray = resultObj.getJSONArray("data");
				mem=new String[jArray.length()][3];
				for (int i = 0; i < jArray.length(); i++) {
	  				JSONObject obj = jArray.getJSONObject(i);
	  				mem[i][0] = obj.getString("id");
	  				mem[i][1] = null;
	  				mem[i][2] = obj.getString("name");
					try {
						mem[i][1] = obj.getString("picture");
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			
			} catch (Exception ex) {
					ex.printStackTrace();
			} catch (FacebookError ext) {
					ext.printStackTrace();
			}

        overlays = mapView.getOverlays();
        markerupdate();
        
        spinnerupdate();
    }
    public void spinnerupdate()
    {
    	if(count <= 1)
    	{
    		Toast.makeText(getApplicationContext(), "기능 지원안함요", 1000).show();
    	}
    	else
    	{
        	spinner.setPrompt("그룹인원 : "+count+"명");
        	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, name);
        	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	spinner.setAdapter(adapter);
    		spinner.setOnItemSelectedListener(this);
    	}

    }
    
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
		gotoSelected();
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}
	
    public void gotoSelected()
    {
    	int pos = spinner.getSelectedItemPosition();
    	Log.i("pos", "   "+pos);
    	String[] lo = locc[pos].split(" ");
    	double lat = Double.parseDouble(lo[0]);
    	double lon = Double.parseDouble(lo[1]);
    	Log.i("pos", "   "+lat + "  "+lon);
    	GeoPoint p = new GeoPoint((int)(lat*1000000), (int)(lon*1000000));
    	mc.animateTo(p);
    	mc.setZoom(17);
    	
    	mapView.invalidate();
    	
    }

    public void markerupdate()
    {
    	double latitude;
		double longitude;
    	double intLatitude,intLongitude;
			
    	Drawable draw = null;
    	GeoPoint p = null;
    	List<OverlayItem> overlayitem = new ArrayList<OverlayItem>();
    	Photo markOverlays = null;
    	
    	locc = new String[mem.length];
    	name = new String[mem.length];
		Log.i("length", "   "+mem.length);
       	LocationDBTransfer locDBTrans = new LocationDBTransfer();
       	try{
   			for (int i = 0; i < mem.length; i++) {
   				
   				String loc = locDBTrans.getLocation(mem[i][0]);
   				Log.i("loc", ""+loc);
   				Log.i("i", ""+i);
   				
   				if(loc.equalsIgnoreCase(" ")==false && locDBTrans.getPermission(mem[i][0]).equalsIgnoreCase("true")){
   					
   					StringTokenizer st = new StringTokenizer(loc, " ");

   					Log.i("Log", "    bbbbbb");
   					String lat = st.nextToken();
   					Log.i("lat", "     "+lat);
   					latitude = Double.parseDouble(lat);				
   					String lon = st.nextToken();
   					longitude = Double.parseDouble(lon);
   					
   					
   					intLatitude = latitude * 1000000;
   					intLongitude = longitude * 1000000;
   					p = new GeoPoint((int)intLatitude, (int)intLongitude);
   					mc.animateTo(p);
   					Log.i("p", "     "+(int)intLatitude+",   "+(int)intLongitude);
   					 Bitmap image= BitmapFactory.decodeStream(new URL(mem[i][1]).openStream());
   					Log.i("url", "     "+new URL(mem[i][1]));
   					 Bitmap cImage = Bitmap.createScaledBitmap(image, 70, 70, true);

   					 draw = new BitmapDrawable(cImage);
   					 overlayitem.add(new OverlayItem(p, "",""));
   					Log.i("draw", "     "+draw);
   					 overlayitem.get(count).setMarker(draw);
   					 markOverlays = new Photo(draw);
   					 markOverlays.addOverlay(overlayitem.get(count));
   					 overlays.add(markOverlays);
   					locc[count] = loc;
   					name[count] = mem[i][2];
   					count++;
   					 
   				}
   				
 			}
       	}
       	catch (Exception ex) {
				ex.printStackTrace();
			}
    
    }

    class Photo extends ItemizedOverlay<OverlayItem>
    {
    	private ArrayList<OverlayItem> m_overlays = new ArrayList<OverlayItem>();
    	
    	public Photo(Drawable defaultMarker)
    	{
    			super(boundCenterBottom(defaultMarker));
    	}
    	
    	public void addOverlay (OverlayItem overlay)
    	{
    		m_overlays.add(overlay);
    		populate();
    	}
    	@Override
    	protected OverlayItem createItem(int i)
    	{
    		return m_overlays.get(i);
    	}
    	
    	@Override
    	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
    		super.draw(canvas, mapView, false); // shadow를 false로하면 이미지의 그림자가 없어짐 
      	}

    	@Override
    	public int size()
    	{
    		return m_overlays.size();
    	}
    	
    	protected boolean onTap(int index)
        {
        	return true;
        }
    }

}



 


